home *** CD-ROM | disk | FTP | other *** search
/ CD Actual 9 / CDACTUAL9.iso / share / Dos / VARIOS / pascal / MEMORY.SWG / 0003_Primer on dynamic memory allocation.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1996-02-21  |  1.0 KB  |  48 lines

  1. {
  2. Q:  How do I reduce the amount of memory taken from the data
  3. segment?  (or How do I allocate memory dynamically?)
  4.  
  5. A:
  6. }
  7. Let's say your data structure looks like this:
  8.  
  9.  type
  10.    TMyStructure = record
  11.      Name: String[40];
  12.      Data: array[0..4095] of Integer;
  13.    end;
  14.  
  15. That's too large to be allocated globally, so instead of 
  16. declaring a global variable,
  17.  
  18.  var
  19.    MyData: TMyStructure;
  20.  
  21. you declare a pointer type,
  22.  
  23.  type
  24.    PMyStructure = ^TMyStructure;
  25.  
  26. and a variable of that type,
  27.  
  28.  var
  29.    MyDataPtr: PMyStructure;
  30.  
  31. Such a pointer consumes only four bytes of the data segment.
  32.  
  33. Before you can use the data structure, you have to allocate it 
  34. on the heap:
  35.  
  36.  New(MyDataPtr);
  37.  
  38. and now you can access it just like you would global data. The 
  39. only difference is that you have to use the caret operator to 
  40. dereference the pointer:
  41.  
  42.  MyDataPtr^.Name := 'Lloyd Linklater';
  43.  MyDataPtr^.Data[0] := 12345;
  44.  
  45. Finally, after you're done using the memory, you deallocate it:
  46.  
  47.  Dispose(MyDataPtr);
  48.